<?php
/**
 * Created by PhpStorm.
 * User: Rain
 * Date: 2020/5/16
 * Time: 13:58
 */

namespace app\admin\service\business\controllers\City\Models;


use app\admin\service\model\BaseModel;
use app\model\Area;

class CityModel extends BaseModel
{
    /**
     * 获取列表
     *
     * @param array $where
     * @param array $field
     * @param bool $isPage
     * @param int $page
     * @return mixed
     */
    public function getList(array $where, array $field = [], bool $isPage = true, int $page = 10)
    {
        $this->page = $page;
        $this->isPage = $isPage;

        $query = Area::field($field ?: ['id', 'name', 'code', 'pid', 'sort', 'status', 'create_time'])
            ->order('sort desc,id asc');

        if ($where) {
            // 标题筛选
            if (isField($where, 'name')) {
                $query->whereLike('name|code', "%{$where['name']}%");
            }

            // 省
            if (isField($where, 'province_id')) {
                $query->where('pid->province_id', (int)$where['province_id']);
            }

            // 市
            if (isField($where, 'city_id')) {
                $query->where('pid->city_id', (int)$where['city_id']);
            }

            // 地区类型
            if (isField($where, 'city_type')) {
                if (0 == $where['city_type']) $query->where('pid->province_id', 0)->where('pid->city_id', 0);

                if (1 == $where['city_type']) $query->where('pid->province_id', '<>', 0)->where('pid->city_id', 0);

                if (2 == $where['city_type']) $query->where('pid->province_id', '<>', 0)->where('pid->city_id', '<>', 0);
            }

            // 时间筛选
            if (isField($where, 'start') && isField($where, 'end')) {
                $query->whereBetweenTime('create_time', $where['start'], $where['end']);
            }
        }

        return $this->all($query);
    }

    /**
     * 获取单条
     *
     * @param int $id
     * @param array $field
     * @return mixed
     */
    public function getFind(int $id, array $field = [])
    {
    }

    /**
     * 添加
     *
     * @param array $data
     * @return mixed
     */
    public function insert(array $data)
    {
    }

    /**
     * 修改
     *
     * @param array $data
     * @param int $id
     * @return mixed
     */
    public function edit(array $data, int $id)
    {
        $this->update(Area::class, array_merge(['id' => $id], $data));
    }

    /**
     * 删除
     *
     * @param int $id
     * @return mixed
     */
    public function delete(int $id)
    {
    }

    /**
     * 通过 ids 获取城市列表
     *
     * @param array $ids
     * @return mixed
     */
    public function getFormIdsCityList(array $ids)
    {
        $this->isPage = false;

        $query = Area::whereIn('id', $ids)->field(['id', 'name']);

        return $this->all($query);
    }
}
